package com.java.hohenheim.springplatform.web.service.register;

import cn.hutool.extra.spring.SpringUtil;
import com.java.hohenheim.springplatform.db.dao.AccountDAO;
import com.java.hohenheim.springplatform.db.dao.UserRoleDAO;
import com.java.hohenheim.springplatform.db.entity.AccountEntity;
import com.java.hohenheim.springplatform.db.entity.UserRoleEntity;
import com.java.hohenheim.springplatform.define.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

/**
 * @author Hohenheim
 * @date 2020/8/9
 * @description 注册模块父类
 */
public abstract class BaseRegister implements IRegister {
    @Autowired
    private AccountDAO mAccountDAO;
    @Autowired
    private UserRoleDAO mUserRoleDAO;

    public boolean addAccountData(AccountEntity entity) {
        PlatformTransactionManager platformTransactionManager = SpringUtil.getBean(PlatformTransactionManager.class);
        TransactionDefinition transaction = SpringUtil.getBean(TransactionDefinition.class);

        boolean addResult = false;
        TransactionStatus transactionStatus = null;

        try {
            transactionStatus = platformTransactionManager.getTransaction(transaction);

            int addAccountResult =  mAccountDAO.getBaseMapper().insertSelective(entity);
            if(addAccountResult > 0) {
                UserRoleEntity roleEntity = new UserRoleEntity();
                roleEntity.setRoleId(UserRole.ROLE_USER.getRoleId());
                roleEntity.setUserId(entity.getUserId());

                addResult = mUserRoleDAO.save(roleEntity);
            }

            if(addResult) {
                platformTransactionManager.commit(transactionStatus);
            }
            else {
                platformTransactionManager.rollback(transactionStatus);
            }
        }
        catch (Exception e) {
            if(null != transactionStatus) {
                platformTransactionManager.rollback(transactionStatus);
            }
        }


        return addResult;
    }
}
